package com.xzh.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wf.captcha.SpecCaptcha;
import com.xzh.constant.RedisConstants;
import com.xzh.model.Users;
import com.xzh.model.search.Account;
import com.xzh.service.UsersService;
import com.xzh.util.JsonResult;
import com.xzh.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.Getter;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@RestController
@RequestMapping(value = "/api/v1/users", produces = MediaType.APPLICATION_JSON_VALUE)
public class UsersApi {
    private UsersService usersService;
    private RedisTemplate<Object, Object> redisTemplate;
    private static final StrongPasswordEncryptor PE = new StrongPasswordEncryptor();
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public UsersApi(UsersService usersService) {
        this.usersService = usersService;
    }


    @GetMapping
    public ResponseEntity<JsonResult<?>> UserList(@RequestParam(defaultValue = "1") Integer pageNo,
                                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                                  Users  users){
        Page<Users> page = new Page<>(pageNo, pageSize);
        page = usersService.selectAll(page, users);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> addUser(@Valid @RequestBody Users users){
        try {
            // 在保存用户前加密密码
            String encryptedPassword = PE.encryptPassword(users.getPassword());
            users.setPassword(encryptedPassword);

            boolean result = usersService.insert(users);
            if(result){
                return ResponseEntity.ok(JsonResult.success());
            }else {
                return ResponseEntity.ok(JsonResult.fail("添加失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(JsonResult.fail("添加用户失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<JsonResult<?>> deleteUser(@PathVariable Integer id){
        boolean result = usersService.deleteById(id);
        if(result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<JsonResult<?>> updateUserStatus(@PathVariable Integer id,
                                                          @Valid @RequestBody Users users){
        users.setUserId(id);
        boolean result = usersService.updateById(users);
        if(result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> updateUser(@Valid @RequestBody Users users){
        boolean result = usersService.updateById(users);
        if(result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    @GetMapping("/captcha")
    public void captcha(String id,HttpServletRequest req, HttpServletResponse resp) throws IOException {
        SpecCaptcha captcha = new SpecCaptcha(140, 40, 4);
        resp.setContentType("image/gif");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        //req.getSession().setAttribute("captcha", captcha.text().toLowerCase());
        redisTemplate.opsForValue().set("captcha-"+id,
                captcha.text().toLowerCase(), Duration.ofMinutes(3));

        captcha.out(resp.getOutputStream());
    }

    @PostMapping("/login")
    public ResponseEntity<JsonResult<?>> login(@RequestBody Account account) {
        try {
            String correct = (String) redisTemplate.opsForValue().get("captcha-"+account.getCaptchaId());
            if (!account.getCaptcha().equals(correct)) {
                return ResponseEntity.ok(JsonResult.fail("验证码不正确"));
            }

            Users user = usersService.findByUsername(account.getUsername());
            if (user == null) {
                return ResponseEntity.ok(JsonResult.fail("用户不存在"));
            }

            //校验密码
            boolean pass = PE.checkPassword(account.getPassword(), user.getPassword());
            if (!pass) {
                return ResponseEntity.ok(JsonResult.fail("密码不正确"));
            }

            //颁发jwt
            String jwt = JwtUtils.createJwt(UUID.randomUUID().toString(), user.getUsername(),
                    Map.of("username", user.getUsername(), "userId", user.getUserId()),
                    LocalDateTime.now().plusMinutes(30), jwtSecret);
            System.out.println(jwt);

            return ResponseEntity.ok(JsonResult.success(jwt));
        } catch (Exception e) {
            return ResponseEntity.ok(JsonResult.fail("登录失败: " + e.getMessage()));
        }
    }

    @GetMapping("/select/{id}")
    public ResponseEntity<JsonResult<?>> selectById(@PathVariable Integer id){
        Users user = usersService.selectById(id);
        return ResponseEntity.ok(JsonResult.success(user));
    }


}
